package teach.shuji.java12.config;

import cn.dev33.satoken.exception.NotPermissionException;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import teach.shuji.java12.common.CommonResult;
import teach.shuji.java12.common.NoDataCommonResult;

@RestControllerAdvice
public class ParamException {


    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public NoDataCommonResult handleNotPermissionException(NotPermissionException e)
    {
        NoDataCommonResult result = new NoDataCommonResult();
        result.setCode(401);
        result.setMsg(e.getMessage());
        return result;
    }


    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败：");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();

        CommonResult<String> result = new CommonResult<>();
        result.setCode(400);
        result.setMsg(msg);
        return result;
    }

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResult<String> handleConstraintViolationException(ConstraintViolationException ex) {
        CommonResult<String> result = new CommonResult<>();
        result.setCode(400);
        result.setMsg(ex.getMessage());
        return result;
    }
}
